package com.leetcode.Offer;

public class JZ29_2 {
    public int[] spiralOrder(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return new int[]{};
        }
        int top = 0;
        int bottom = matrix.length - 1;
        int left = 0;
        int right = matrix[0].length - 1;
        int index = 0;
        int[] res = new int[(bottom + 1) * (right + 1)];
        while (top <= bottom && left <= right) {
            // 上
            for (int j = left; j <= right; j++) {
                res[index++] = matrix[top][j];
            }
            // 右
            for (int i = top + 1; i <= bottom; i++) {
                res[index++] = matrix[i][right];
            }
            if (top < bottom && left < right) {
                // 下
                for (int j = right - 1; j > left; j--) {
                    res[index++] = matrix[bottom][j];
                }
                // 左
                for (int i = bottom; i > top; i--) {
                    res[index++] = matrix[i][left];
                }
            }
            left++;
            right--;
            top++;
            bottom--;
        }
        return res;
    }
}
